<script lang="ts" setup>
  import { ref, computed, onBeforeMount } from 'vue';
  import type { Ref } from 'vue';
  import { Affix, Avatar, Menu, MenuItem } from '@arco-design/web-vue';
  import { RouterLink, useRoute } from 'vue-router';
  import type { ColumnRecord } from '/@/api/app/model/articleModel';
  import IconRecommended from '/@/assets/svg/recommended.svg';
  import { pick } from 'lodash-es';
  import { queryAppColumnList } from '/@/api/app/article';

  const route = useRoute();

  // 当前栏目 id
  const DEFAULT_COLUMN_ID = 100;
  // 默认栏目 id
  const FOLLOWING_COLUMN_ID = 101;

  const getCurrentColumnId = computed(() => {
    if (route.path === '/column') {
      // 默认的时候 id 0 会获取为 undefined
      return parseInt(route.query.column_id as string, 10) || undefined;
    }
    if (route.path === '/column/following') {
      return FOLLOWING_COLUMN_ID;
    }
    // 默认的时候 id 0 会获取为 undefined
    return parseInt(route.query.column_id as string, 10) || undefined;
  });

  // 栏目选中
  const getColumnMenuSelectedKeys = computed(() => {
    return getCurrentColumnId.value ? [getCurrentColumnId.value + ''] : [DEFAULT_COLUMN_ID + ''];
  });

  // 栏目列表
  const columnList = ref<ColumnRecord[]>([]);

  // 栏目菜单列表
  type ColumnMenuItemRecord = Pick<ColumnRecord, 'id' | 'name' | 'icon'> & {
    key: string;
    to: number | undefined;
    outer?: boolean;
  };
  const columnMenuList: Ref<ColumnMenuItemRecord[]> = computed(() => {
    return [
      {
        id: DEFAULT_COLUMN_ID,
        key: DEFAULT_COLUMN_ID + '',
        to: '/column',
        name: '全部',
        icon: IconRecommended,
        outer: true,
      },
      {
        id: FOLLOWING_COLUMN_ID,
        key: FOLLOWING_COLUMN_ID + '',
        to: '/column/following',
        name: '关注',
        icon: IconRecommended,
        outer: true,
      },
      ...columnList.value.map((item) => {
        return {
          ...pick(item, ['id', 'name', 'icon']),
          key: item.id + '',
          to: item.id,
        };
      }),
    ];
  });

  const calculateTo = (item: ColumnMenuItemRecord) => {
    return item.outer ? { path: item.to } : { path: '/column', query: { column_id: item.to } };
  };

  // 获取栏目
  onBeforeMount(async () => {
    columnList.value = await queryAppColumnList({ name: '' });
  });
</script>

<template>
  <div class="w-[180px] rounded-lg">
    <Affix :offsetTop="90">
      <Menu
        class="rounded-[3px] pt-[4px]"
        mode="vertical"
        :accordion="true"
        :selectedKeys="getColumnMenuSelectedKeys"
      >
        <RouterLink v-for="item in columnMenuList" :key="item.id" :to="calculateTo(item)">
          <MenuItem :key="item.key">
            <template #icon>
              <Avatar class="w-[16px] h-[16px]" :imageUrl="item.icon" />
            </template>
            {{ item.name }}
          </MenuItem>
        </RouterLink>
      </Menu>
    </Affix>
  </div>
</template>
